package com.it.jzs.service.admin.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.it.jzs.dao.admin.AdminCustomMapper;
import com.it.jzs.pojo.Custom;
import com.it.jzs.service.admin.AdminCustomService;
import com.it.jzs.vo.Result;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AdminCustomServiceImpl implements AdminCustomService {
    @Resource
    private AdminCustomMapper adminCustomMapper;

    @Override
    public Result<Object> selectAll() {
        QueryWrapper<Custom> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("custom_id").last("limit 1");

        Custom custom = adminCustomMapper.selectOne(wrapper);
        return Result.success(custom, "获取成功");
//        return null;
    }

    @Override
    public Result<Object> update(Custom sourcustom) {  // 为什么这么做，因为涉及到没有用户id的关联，况且，如果删除了id，那么这个硬编码就很难修改
        // 直接先插入一条新的记录 ,要先查询之前的 记录
        List<Custom> customs = adminCustomMapper.selectList(null);
        if (customs.size() == 0) {
            sourcustom.setUpdateTime(System.currentTimeMillis());
            sourcustom.setCreateTime(System.currentTimeMillis());
            adminCustomMapper.insert(sourcustom);
        }
        QueryWrapper<Custom> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("custom_id").last("limit 1");

        Custom custom = adminCustomMapper.selectOne(wrapper);
        System.out.println("custom = " + custom);
        String customAdverBody = sourcustom.getCustomAdverBody();
        String customAdverImg = sourcustom.getCustomAdverImg();
        String customHead = sourcustom.getCustomHead();
        String customLocation = sourcustom.getCustomLocation();
        String customName = sourcustom.getCustomName();
        if (customAdverBody == null) {  // 如果提交的数据为空，就把查到的数据赋值给它，然后再一起插入
            sourcustom.setCustomAdverBody(custom.getCustomAdverBody());
        }
        if (customAdverImg == null) {
            sourcustom.setCustomAdverImg(custom.getCustomAdverImg());
        }
        if (customHead == null) {
            sourcustom.setCustomHead(custom.getCustomHead());
        }
        if (customLocation == null) {
            sourcustom.setCustomLocation(custom.getCustomLocation());
        }
        if (customName == null) {
            sourcustom.setCustomName(custom.getCustomName());
        }
//        if(custom.getCustomAdverImg()!=null&&)
        sourcustom.setCreateTime(custom.getCreateTime());
        sourcustom.setUpdateTime(System.currentTimeMillis());
        int insert = adminCustomMapper.insert(sourcustom);
        if (insert > 0) {
            return Result.success(null, "修改成功");
        }
        return Result.error(null, "新增失败");
    }
}
